<?php

namespace App\EventListener;

use App\Utils\Annotation\ApiAuthority;
use App\Utils\Annotation\ApiParam;
use App\Utils\Helper\ApiHelper;
use Doctrine\Common\Annotations\AnnotationReader;
use Symfony\Component\HttpKernel\Event\ControllerEvent;

class ApiListener {

    private $annotationReader;

    public function __construct () {
        $this->annotationReader = new AnnotationReader();
    }

    public function onKernelController (ControllerEvent $event): void {
        if (!$event->isMasterRequest()) {
            return;
        }

        $controllers = $event->getController();
        if (!is_array($controllers)) {
            return;
        }

        [$controller, $method] = $controllers;

        $this->handleApi($controller, $method);
    }

    /**
     * API数据整理
     * @param $controller
     * @param string $method
     * @throws \Throwable
     */
    private function handleApi ($controller, string $method): void {
        $ref = new \ReflectionClass($controller);
        $method = $ref->getMethod($method);
        $annotations = $this->annotationReader->getMethodAnnotations($method);
        foreach ($annotations as $annotation) {
            // 记录声明权限
            if ($annotation instanceof ApiAuthority) {
                ApiHelper::getInstance()->setAuthority($annotation);
            }
            // 记录声明参数
            if ($annotation instanceof ApiParam) {
                ApiHelper::getInstance()->setParameter($annotation);
            }
        }
    }
}